<template>
  <div>
    <audio ref="audio">
      <source :src="mp3Url">
    </audio>

    <n-space justify="space-between">
      <n-el style="width: 1000px">
        <n-popconfirm
            @positive-click="()=>{
              startInterrogateTask()
            }"
        >
          <template #trigger>
            <n-button type="primary" style="margin-bottom: 10px">批量反推关键词</n-button>
          </template>
          <n-grid>
            <n-grid-item :span="24">
              反推类型: <n-select :options="describeModelOption" v-model:value="selectDescribeModel"></n-select>
            </n-grid-item>
            <n-grid-item :span="24">
              全部分镜将重新反推关键词，是否确认?
            </n-grid-item>
          </n-grid>
        </n-popconfirm>
        <n-divider vertical></n-divider>
        <n-button
            type="primary"
            style="margin-bottom: 10px;"
            @click="initBatchOperationForm">
          批量出图
        </n-button>
        <n-divider vertical></n-divider>
        <n-button type="primary" style="margin-bottom: 10px;" @click=" upscaleList = boardList ; upscaleModalShow = true">
          后期放大
        </n-button>
        <n-divider vertical></n-divider>
        <n-popconfirm
            @positive-click="batchChosePic"
        >
            <template #trigger>
                <n-button type="primary" style="margin-bottom: 10px">批量选图</n-button>
            </template>
            <n-grid>
                <n-grid-item :span="24">
                    <n-input-number
                    :show-button="false"
                    placeholder="请输入图片编号"
                    v-model:value="batchChoseNum">
                    </n-input-number>
                </n-grid-item>
                <n-grid-item :span="24">
                    全部分镜将重新选图，是否确认?
                </n-grid-item>
            </n-grid>
        </n-popconfirm>
        <n-divider vertical></n-divider>
        <n-button type="primary" style="margin-bottom: 10px;" @click="privilegeModal = true">
          关键词提权
        </n-button>
      </n-el>
      <n-el>
        <n-row>
          <n-select
              style="width: 200px;"
              :options="storyBoardSelectType"
              v-model:value="storyBoardSelectOption"
              @update:value="getStoryBoardByChapterId">
          </n-select>
        </n-row>
      </n-el>
    </n-space>
    <n-data-table
        ref="storyBoardTableRef"
        :single-line="false"
        :bordered="true"
        :loading="tableLoading"
        :bottom-bordered="true"
        :columns="createColumns"
        :data="boardList"
        :style="{ height: `${clientHeight - 159}px` }"
        flex-height
    />
    <n-modal v-model:show="imageModelShow">
      <n-card
          style="width: 500px"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
      >
        <img-model :row="selectRow"></img-model>
      </n-card>
    </n-modal>

    <n-drawer v-model:show="detailDesignShow" :width="drawerWidth" :close-on-esc="false"
              @after-leave="getStoryBoardByChapterId">
      <n-drawer-content title="画面高级调整" :closable="true">
        <detailDesign
            :story-board-list="boardList"
            :select-num="selectIndex"
            :reload-story-boards="getStoryBoardByChapterId"
        ></detailDesign>
      </n-drawer-content>
    </n-drawer>


    <n-modal
        v-model:show="progressModal"
        :mask-closable=false
        class="custom-card"
        style="width: 500px"
        preset="card"
        title="任务进度"
        size="huge"
        :bordered="false"
        @close="modalClose"
    >
      <n-space justify="space-around">
        <n-statistic label="当前进度" :value="currentTaskNum">
          <template #prefix>
          </template>
          <template #suffix>
            / {{ boardList.length }}
          </template>
        </n-statistic>
        <n-statistic label="成功/失败">
          <template #prefix>
            {{ taskStatus.successNum }}
          </template>
          <template #suffix>
            / {{ taskStatus.failNum }}
          </template>
        </n-statistic>
      </n-space>
      <n-progress
          type="line"
          :percentage=" Math.round(currentTaskNum/boardList.length*100) "
          :height="30"
          :border-radius="5"
          :fill-border-radius="0"
      />
    </n-modal>


    <n-modal
        v-model:show="batchOperationForm.batchOperationModalShow"
        :mask-closable=false
    >
      <n-card
          style="width: 600px"
          title="自动任务"
          :bordered="false"
          size="huge">
        <n-form>
          <n-form-item label="任务类型">
            <n-radio-group v-model:value="batchOperationForm.batchOperationType">
              <n-radio value='0' v-if="voiceConfig && voiceConfig.planType ==='systemVoice' ">生成图片和音频</n-radio>
              <n-radio value="1">仅生成图片</n-radio>
              <n-radio value="2" v-if="voiceConfig && voiceConfig.planType ==='systemVoice' ">仅生成音频</n-radio>
            </n-radio-group>
          </n-form-item>
          <n-grid x-gap="10">
            <n-grid-item :span="12">
              <n-form-item label="开始序号">
                <n-input-number :precision="0"
                                v-model:value="batchOperationForm.batchOperationStartNum"></n-input-number>
              </n-form-item>
            </n-grid-item>
            <n-grid-item :span="12">
              <n-form-item label="结束序号">
                <n-input-number :precision="0" v-model:value="batchOperationForm.batchOperationEndNum"></n-input-number>
              </n-form-item>
            </n-grid-item>
            <n-grid-item :span="12">
              <n-form-item :show-label="false">
                <n-checkbox v-model:checked="skipFlag">跳过已完成</n-checkbox>
              </n-form-item>
            </n-grid-item>
          </n-grid>
          <n-grid ref="progressGridRef" v-if="taskStatus.totalNum!=0">
            <n-grid-item :span="24">
              <n-space justify="space-around">
                <n-statistic label="当前进度" :value="currentTaskNum">
                  <template #prefix>
                  </template>
                  <template #suffix>
                    / {{ taskStatus.totalNum }}
                  </template>
                </n-statistic>
                <n-statistic label="成功/失败">
                  <template #prefix>
                    {{ taskStatus.successNum }}
                  </template>
                  <template #suffix>
                    /
                    <n-gradient-text type="error">{{ taskStatus.failNum }}</n-gradient-text>
                  </template>
                </n-statistic>
              </n-space>
            </n-grid-item>
            <n-grid-item :span="24">
              <n-progress
                  type="line"
                  :percentage=" Math.round((currentTaskNum/taskStatus.totalNum) * 100) "
                  :height="30"
                  :border-radius="5"
                  :fill-border-radius="0"
                  :indicator-placement="'inside'"
                  :processing="batchOperationForm.batchOperationFlag"
              />
            </n-grid-item>
          </n-grid>
        </n-form>

        <template #footer>
          <n-space justify="space-between">
            <n-button
                type="primary"
                @click="startTask"
                :loading="batchOperationForm.loading"
                v-if="!batchOperationForm.batchOperationFlag">开始任务
            </n-button>
            <n-button
                type="warning"
                v-if="!batchOperationForm.batchOperationFlag"
                @click="batchOperationForm.batchOperationModalShow = false">取消
            </n-button>
          </n-space>
          <n-button
              :block="true"
              type="error"
              style="margin-top:5px;"
              @click="shutDownTask"
              v-if="batchOperationForm.batchOperationFlag">终止任务
          </n-button>
        </template>
      </n-card>
    </n-modal>
    <n-modal
        v-model:show="upscaleModalShow"
        :mask-closable=false
        :closable="true"
    >
      <UpscalerView
          :paintConfig="paintConfig"
          :resourceId="resourceId"
          :upsacleList="upscaleList"
          :closeFunction="upscalerViewClose"
          :storyId="props.story.id"
          paintEngineType="Fooocus">
      </UpscalerView>
    </n-modal>


    <n-modal
        v-model:show="repaintModelShow"
        transform-origin="center"
    >
      <ReapintView :inPaintAction="inpaint" :storyBoard="inPaintStoryBoard" :closeAction="repaintModalClose">
      </ReapintView>
    </n-modal>

    <n-modal
        v-model:show="batchInterrogateProgressModal"
        :mask-closable=false
        class="custom-card"
        style="width: 500px"
        preset="card"
        title="任务进度"
        size="huge"
        :bordered="false"
        @close="modalClose"
    >
      <n-space justify="space-around">
        <n-statistic label="当前进度" :value="taskStatus.successNum + taskStatus.failNum">
          <template #prefix>
          </template>
          <template #suffix>
            / {{ taskStatus.totalNum }}
          </template>
        </n-statistic>
        <n-statistic label="成功/失败">
          <template #prefix>
            {{ taskStatus.successNum }}
          </template>
          <template #suffix>
            / {{ taskStatus.failNum }}
          </template>
        </n-statistic>
      </n-space>
      <n-progress
          type="line"
          :percentage=" Math.round((taskStatus.successNum + taskStatus.failNum) / taskStatus.totalNum * 100) "
          :height="30"
          :border-radius="5"
          :fill-border-radius="0"
      />
    </n-modal>

    <n-modal
      v-model:show="privilegeModal"
      :mask-closable=false
      class="custom-card"
      preset="card"
      :style="{
          width: '600px'
      }"
      title="关键词提权"
      size="huge"
      :bordered="false"
    >
      <n-form style="width: 500px">
        <n-form-item label="关键词">
          <n-dynamic-tags type="primary" v-model:value="privilegeForm.tags"></n-dynamic-tags>
        </n-form-item>
        <n-form-item label="关键词权重">
          <n-slider v-model:value="privilegeForm.value" :max="1.8" :min="0.8" :step="0.1"></n-slider>
        </n-form-item>
        <n-space justify="end">
          <n-button type="primary" :loading="privilegeLoading" @click="privilegeSubmit">确认</n-button>
        </n-space>
      </n-form>
    </n-modal>

  </div>
</template>
<script setup lang="ts">
import {
  NButton,
  NGrid,
  NIcon,
  NImage,
  NInput,
  NPopselect,
  NRadio,
  NRadioGroup,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui'
import {h, nextTick, onMounted, reactive, ref, watch} from "vue"
import {storyController} from "@/api/story/story.api"
import imgModel from '@/views/pages/create/novel/components/imgModel.vue'
import detailDesign from '@/views/pages/create/novel/components/detailDesign.vue'
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {storyBoardController} from "@/api/controller/story/storyBoard.api"
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
import {
  CaretForwardCircleSharp as CaretForwardCircleSharpIcon,
} from '@vicons/ionicons5'
import {creatorDict} from '@/dictionary/creatorDict'
import {paintArtEnums} from "@/enums/paintArtEnums";
import Bus from "@/components/file/box/GlobalUploader/utils/bus";
import {fooocusDict} from "@/dictionary/fooocusDict";
import UpscalerView from "@/components/creator/function/upscaler.vue";
import ReapintView from '@/components/creator/function/repaint.vue'
import {sysParamController} from "@/api/controller/sysParamController";


const {describeModelOption} =  fooocusDict()
const message = useMessage()
const tableLoading = ref(false)
const imageModelShow = ref(false)
const detailDesignShow = ref(false)
const selectRow = ref(null)
const selectIndex = ref(0)
const currentTaskNum = ref(0)
const progressModal = ref(false)
const boardList = ref([])
const mp3Url = ref('')
const audio = ref(null)
const drawerWidth = ref(0)
const privilegeModal = ref(false)
const {storyBoardSelectType, expandImageOption,fooocusVaryOptions,fooocusUpscaleEngineTypeOptions} = creatorDict()
const selectDescribeModel = ref('Anime')
const storyBoardSelectOption = ref("0")
const storyBoardTableRef = ref(null)
const upscaleModalShow = ref(false)
const resourceId = ref(null)
const paintConfig = ref(null)
const stopLoop = ref(false)
const skipFlag = ref(true)
const runInBack = ref(true)
const voiceConfig = ref(null)
const batchChoseNum = ref()
const upscaleList = ref([])
const repaintModelShow = ref(false)
const inPaintStoryBoard = ref(null)
const privilegeLoading = ref(false)
const privilegeForm = reactive({
  value: 1.2,
  tags: ['1girl', '1boy']
})
const wd14Model = ref('local')

const batchInterrogateProgressModal = ref(false)
const batchOperationForm = reactive({
  batchOperationType: '0',
  batchOperationLoading: false,
  batchOperationModalShow: false,
  batchOperationStartNum: 0,
  batchOperationEndNum: 0,
  batchOperationAppointFlag: false,
  batchOperationFlag: false,
  loading: false
})


const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

// 任务状态
const taskStatus = ref({
  successNum: 0,
  failNum: 0,
  totalNum: 0
})

const props = defineProps({
  story: {
    type: Object,
    default: () => {
      return {}
    }
  },
  recoverGetTaskInfo: {
    type: Function,
    required: true
  }
})



// 列表字段
const createColumns = [
  {
    title: '序号',
    key: 'orderNum',
    width: 40,
    align: 'center'
  },
  {
    title: '原文描述',
    key: 'content',
    titleAlign: 'center',
    width: 200,
    render(row, index) {
      return h(NInput, {
        value: row.content,
        readonly: true,
        type: 'textarea',
        style: 'height: 150px'
      })
    }
  },
  {
    title: '关键词',
    key: 'prompt',
    width: 200,
    titleAlign: 'center',
    render(row, index) {
      return h(NInput, {
        value: row.prompt,
        type: 'textarea',
        style: 'height: 150px',
        onBlur() {
          if (boardList.value[index]?.isChange) {
            updateBoard(boardList.value[index])
          }
        },
        onUpdateValue(v) {
          if (v != boardList.value[index].prompt) {
            boardList.value[index].prompt = v
            boardList.value[index].isChange = true
          }
        }
      })
    }
  },
  {
    title: '音频',
    align: 'center',
    key: 'characterName',
    titleAlign: 'center',
    width: 60,
    render(row, index) {
      if (row.audioFileId) {
        return h(NIcon, {
          size: 20,
          onClick: () => {
            audio.value.src = fileFunction.getViewFilePathByUserFileId(row.audioFileId)
            audio.value.play()
          }
        }, {default: () => h(CaretForwardCircleSharpIcon)})
      } else {
        return '暂无'
      }
    }
  },
  {
    title: '参考图',
    key: 'prompt',
    width: 150,
    align:'center',
    render(row) {
      return h(NImage, {
        lazy: true,
        height: '150',
        width: '150',
        objectFit: 'contain',
        src: fileFunction.getViewFilePathByUserFileId(row.examplePic)
      })
    }
  },
  {
    title: '配图',
    key: 'prompt',
    width: 150,
    align: 'center',
    render(row) {
      if (row.imgStatus === "SUBMITTED") {
        return "正在生成"
      }
      if (row.imgFileId == null || row.imgFileId.length === 0) {
        return '等待生成'
      }
      return h(NImage, {
        lazy: true,
        height: '150',
        width: '150',
        objectFit: 'contain',
        src: fileFunction.getViewFilePathByUserFileId(row.imgFileId)
      })
    }
  },
  {
    title: '配图集',
    key: 'prompt',
    align: 'center',
    width: 150,
    render(row, index) {
      if (row.imageList.length === 0) {
        return '等待生成';
      }
      return h(
          'div',
          {
            // style: 'min-height: 22px',
            onClick: () => {
              selectRow.value = row
              imageModelShow.value = true
            }
          },
          h(NImage, {
            lazy: true,
            previewDisabled: true,
            height: '150',
            width: '150',
            objectFit: 'contain',
            src: fileFunction.getViewFilePathByUserFileId(row.imageList[0])
          })
      )
    }
  },
  {
    title: '操作',
    width: 80,
    align: 'center',
    render(row, index) {
      return [
        h(NButton, {
          size: 'small',
          block: true,
          loading: row.interrogateLoading,
          type: 'info',
          onClick: () => interrogate(row)
        }, {
          default: () => '反推关键词'
        }),
        h(NButton, {
          size: 'small',
          block: true,
          style: 'margin-top: 10px',
          loading: row.buttonLoading,
          type: 'info',
          onClick: () => rePaint(row)
        }, {
          default: () => '生成图片'
        }),
        h(NButton, {
          size: 'small',
          block: true,
          style: 'margin-top: 10px',
          type: 'info',
          loading: row.audioButtonLoading,
          onClick: () => reTts(row)
        }, {
          default: () => '生成音频'
        }),
        h(NButton, {
          size: 'small',
          block: true,
          style: 'margin-top: 10px',
          type: 'info',
          loading: row.upscaleLoading,
          onClick: () => upsacleLocal(row)
        }, {
          default: () => '本地放大'
        })
      ]
    }
  },
  {
    title: '特色功能',
    width: 80,
    align: 'center',
    render(row, index) {
      return [
        h(
            NPopselect, {
              options: fooocusUpscaleEngineTypeOptions.value,
              trigger: 'click',
              onUpdateValue: (key: string) => {
                varyImage(row, key)
              },
            }, {
              default: () => {
                return h(
                    NButton,
                    {
                      size: 'small',
                      type: 'primary',
                      block: true,
                      loading: row.varyLoading
                    },
                    {default: () => '扩散放大'}
                )
              }
            }
        ),

        h(
            NPopselect, {
              options: fooocusVaryOptions.value,
              trigger: 'click',
              onUpdateValue: (key: string) => {
                varyImage(row, key)
              },
            }, {
              default: () => {
                return h(
                    NButton,
                    {
                      size: 'small',
                      type: 'primary',
                      style: 'margin-top: 10px',
                      block: true,
                      loading: row.varyLoading
                    },
                    {default: () => '图片变化'}
                )
              }
            }
        ),

        h(
            NPopselect, {
              options: expandImageOption.value,
              trigger: 'click',
              onUpdateValue: (key: string) => {
                expandImage(row, key)
              },
            }, {
              default: () => {
                return h(
                    NButton,
                    {
                      size: 'small',
                      type: 'primary',
                      style: 'margin-top: 10px',
                      block: true,
                      loading: row.expandLoding
                    },
                    {default: () => '图片扩展'}
                )
              }
            }
        ),
        h(
            NButton, {

              size: 'small',
              type: 'warning',
              style: 'margin-top: 10px',
              block: true,
              loading: row.expandLoding,
              onClick: () => {
                inPaintStoryBoard.value = row
                repaintModelShow.value = true
              }

            }, {
              default: () =>  '局部重绘'
        // {
        //         return h(
        //             NButton,
        //             {
        //               size: 'small',
        //               type: 'warning',
        //               style: 'margin-top: 10px',
        //               block: true,
        //               loading: row.expandLoding
        //             },
        //             {default: () => '局部重绘'}
        //         )
        //       }
            }
        )
      ]
    }
  }
]




const getStoryBoardByChapterId = () => {
  tableLoading.value = true
  storyController.getStoryScheduleByChapterId(props.story.id, storyBoardSelectOption.value).then(res => {
    tableLoading.value = false
    if (res.code === 200) {
      boardList.value = res.data
    } else {
      message.error(res.msg)
    }
  })
}


const updateBoard = (row: any) => {
  storyBoardController.addOrUpdateBoard(row).then(res => {
    if (res.code !== 200) {
      message.error(res.msg)
    }
  })
}

/**
 * 重绘
 * @param row
 */
const rePaint = (row: any) => {
  // 设置当前状态为已提交
  row.buttonLoading = true
  storyBoardController.rePaintStoryBoardAndCheck(row.id, 3 * 60 * 1000).then(res => {
    if (res.taskStatus === 'SUCCESS') {
      const imageFiles = res.userFileId.split(',')
      row.imgFileId = imageFiles[0]
      for (let i = 0; i < imageFiles.length; i++) {
        row.imageList.push(imageFiles[i])
      }
    }else {
      window.$notification.error({
        title: "请求错误",
        content: paintArtEnums.stableDiffusion_not_online,
        duration: 5000,
        keepAliveOnHover: true
      })
    }
  }).finally(() => {
    row.buttonLoading = false
  })
}

const reTts = async (row: any) => {
  row.audioButtonLoading = true
  const res = await storyBoardController.reTtsStoryBoardAndCheck(row.id, 30 * 1000).catch(res => {
    message.error("系统异常,请稍后再试")
  }).finally(() => {
    row.audioButtonLoading = false
  })
  if (res.taskStatus === 'SUCCESS') {
    row.audioFileId = res.userFileId
  }
}


// 批量反推关键词
const startInterrogateTask = async () => {
  stopLoop.value = false
  currentTaskNum.value = 0
  taskStatus.value = {
    successNum: 0,
    failNum: 0
  }
  progressModal.value = true
  for (const item of boardList.value) {
    if (stopLoop.value) {
      break
    }
    currentTaskNum.value++
    try {
      const res = await storyBoardController.interrogate(item.id,selectDescribeModel.value)
      if (res.code === 200) {
        console.log(res.data)
        // 成功
        taskStatus.value.successNum++
      } else {
        // 失败
        taskStatus.value.failNum++
      }
    } catch (e) {
      taskStatus.value.failNum++
      message.error("系统异常,请稍后再试")
      break
    }
  }
  // 重载数据
  getStoryBoardByChapterId()
}

const startTask = async () => {
  if (runInBack.value) {
    const param = {
      operationType: batchOperationForm.batchOperationType,
      storyId: props.story.id,
      skipFlag: skipFlag.value,
      startNum: batchOperationForm.batchOperationStartNum,
      endNum: batchOperationForm.batchOperationEndNum
    }
    batchOperationForm.loading = true
    storyController.startStoryBatchTask(param).then(res => {
      if (res.code === 200) {
        props.recoverGetTaskInfo()
      }
    }).finally(() => {
      batchOperationForm.loading = false
      batchOperationForm.batchOperationModalShow = false
    })
  } else {
    stopLoop.value = false
    currentTaskNum.value = 0
    taskStatus.value = {
      successNum: 0,
      failNum: 0,
      totalNum: batchOperationForm.batchOperationEndNum - batchOperationForm.batchOperationStartNum + 1
    }
    batchOperationForm.batchOperationFlag = true
    for (let i = batchOperationForm.batchOperationStartNum;
         i <= batchOperationForm.batchOperationEndNum;
         i++) {
      if (stopLoop.value) {
        break
      }
      currentTaskNum.value++
      const item = boardList.value[i]
      if (batchOperationForm.batchOperationType === '0' || batchOperationForm.batchOperationType === '1') {
        if (skipFlag.value) {
          if (item.imgFileId != null && item.imgFileId.length > 0) {
            // 跳过
            taskStatus.value.successNum++
            continue
          }
        }
        // 开启绘画任务
        try {
          if (batchOperationForm.batchOperationType === '0') {
            // 同步发送
            await storyController.reTtsStoryBoard(item.id)
          }
          const res = await storyBoardController.rePaintStoryBoardAndCheck(item.id, 1.5 * 60 * 1000)
          if (res.taskStatus === 'SUCCESS') {
            // 成功
            taskStatus.value.successNum++
          } else {
            // 失败
            taskStatus.value.failNum++
          }
        } catch (e) {
          taskStatus.value.failNum++
        }
      } else {
        try {
          if (skipFlag.value) {
            if (item.audioFileId != null && item.audioFileId.length > 0) {
              // 跳过
              taskStatus.value.successNum++
              continue
            }
          }
          const res_tts = await storyBoardController.reTtsStoryBoardAndCheck(item.id, 30 * 1000)
          if (res_tts.status === 'SUCCESS') {
            // 成功
            taskStatus.value.successNum++
          } else {
            // 失败
            taskStatus.value.failNum++
          }
        } catch (e) {
          taskStatus.value.failNum++
        }
      }
    }
    // batchOperationForm.batchOperationModalShow = false
    batchOperationForm.batchOperationFlag = false
    // 重载数据
    getStoryBoardByChapterId()
  }
}


const shutDownTask = () => {
  window.$dialog.warning({
    title: "提示",
    content: "是否停止任务?",
    positiveText: "确认",
    negativeText: "取消",
    onPositiveClick: () => {
      stopLoop.value = true
      batchOperationForm.batchOperationFlag = false
      batchOperationForm.batchOperationModalShow = false
    }
  })
}



onMounted(() => {
  getStoryBoardByChapterId()
  getStoryPaintConfig()
  drawerWidth.value = window.innerWidth
  window.addEventListener('resize', handleResize)
})

// 窗口宽度变化
const handleResize = () => {
  drawerWidth.value = window.innerWidth;
}

// 推理关键词
const interrogate = (row: any) => {
  row.interrogateLoading = true
  storyBoardController.interrogate(row.id,selectDescribeModel.value).then(res => {
    row.interrogateLoading = false
    if (res.code === 200) {
      const data = res.data;
      console.log(data);
      row.prompt = data
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    row.interrogateLoading = false
  })
}

const upsacle = (row: any) => {
  upscaleList.value = [row]
  upscaleModalShow.value = true
}



const varyImage = (row:any, varyType:string) =>{
  row.varyLoading = true
  const param = {
    uov_method: varyType,
    storyBoardId: row.id
  }
  storyBoardController.asyncFooocusVaryStoryBoardAndCheck(param, 10 * 1000 *60).then(res => {
    if (res.taskStatus === 'SUCCESS') {
      const imageFiles = res.userFileId.split(',')
      row.imgFileId = imageFiles[0]
      for (let i = 0; i < imageFiles.length; i++) {
        row.imageList.push(imageFiles[i])
      }
    }else {
      window.$notification.error({
        title: "请求异常:",
        content: res.failReason,
        duration: 5000,
        keepAliveOnHover: true
      })
    }
  }).finally(() => {
    row.varyLoading = false
  })
}

const expandImage = (row: any, expandDirection: string) => {
  row.expandLoding = true
  let expand = 'Top,Bottom'
  if (expandDirection=='HORIZONTAL'){
    expand = "Left,Right"
  }
  storyBoardController.asyncFooocusExpandStoryBoardAndCheck(expand,row.id, 10 * 1000 *60).then(res => {
    if (res.taskStatus === 'SUCCESS') {
      const imageFiles = res.userFileId.split(',')
      row.imgFileId = imageFiles[0]
      for (let i = 0; i < imageFiles.length; i++) {
        row.imageList.push(imageFiles[i])
      }
    }else {
      window.$notification.error({
        title: "请求异常:",
        content: res.failReason,
        duration: 5000,
        keepAliveOnHover: true
      })
    }
  }).finally(() => {
    row.expandLoding = false
  })
}


const getStoryPaintConfig = () => {
  storyController.getStoryPaintConfig(props.story.id).then(res => {
    if (res.code === 200) {
      if (res.data != null) {
        resourceId.value = res.data.resourceId
        paintConfig.value = JSON.parse(res.data.paintConfigText)
        voiceConfig.value = JSON.parse(res.data.voiceConfigText)
      }
    } else {
      message.error(res.msg);
    }
  })
}

const modalClose = () => {
  stopLoop.value = true
  progressModal.value = false
  skipFlag.value = true
}


const initBatchOperationForm = () => {
  if(voiceConfig.value?.planType === 'systemVoice'){
    batchOperationForm.batchOperationType = '0'
  }else {
    batchOperationForm.batchOperationType = '1'
  }
  batchOperationForm.batchOperationStartNum = 0
  batchOperationForm.batchOperationEndNum = boardList.value.length - 1
  batchOperationForm.batchOperationAppointFlag = false
  batchOperationForm.batchOperationModalShow = true
  taskStatus.value.totalNum = 0
  taskStatus.value.successNum = 0
  taskStatus.value.failNum = 0
}

const batchChosePic = () =>{
    if (!batchChoseNum.value){
        window.$message.warning('请填写图片编号')
    }
    const param = {
        storyId: props.story.id,
        choseNum: batchChoseNum.value
    }
    storyController.batchChosePic(param).then(res => {
        if (res.code === 200) {
            window.$message.success('操作成功')
            getStoryBoardByChapterId()
        } else {
            window.$message.error(res.msg)
        }
    })
}


const upscalerViewClose = () => {
  upscaleModalShow.value = false
  getStoryBoardByChapterId()
}

const repaintModalClose = () =>{
  repaintModelShow.value = false
}


const inpaint = async (base64:string, prompt:string , storyBoardId:string) =>{
  inPaintStoryBoard.value.expandLoding = true
  repaintModelShow.value = false
  const param = {
    mask: base64,
    prompt: prompt,
    storyBoardId: storyBoardId
  }
  storyBoardController.asyncFooocusInpaintStoryBoardAndCheck(param,10*60*1000).then(res=>{
    if (res.taskStatus === 'SUCCESS') {
      const imageFiles = res.userFileId.split(',')
      inPaintStoryBoard.value.imgFileId = imageFiles[0]
      for (let i = 0; i < imageFiles.length; i++) {
        inPaintStoryBoard.value.imageList.push(imageFiles[i])
      }
    }else {
      window.$notification.error({
        title: "请求异常:",
        content: res.failReason,
        duration: 5000,
        keepAliveOnHover: true
      })
    }
  }).finally(()=>{
    inPaintStoryBoard.value.expandLoding = false
  })
}


const upsacleLocal = (row: any) => {
  const param = {
    scale: 2,
    upscaleEngine: 'realesrgan',
    modelName: 'realesr-animevideov3',
    skipFlag: 'false',
    storyBoardId: row.id,
    storyId: props.story.id
  }
  row.upscaleLoading = true
  storyBoardController.upscale(param).then(res => {
    row.interrogateLoading = false
    if (res.code === 200) {
      row.imageList.push(res.data)
      row.imgFileId = res.data
      updateBoard(row)
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    row.upscaleLoading = false
  })
}
const privilegeSubmit = () =>{
  const param = {
    storyId: props.story.id,
    keyWrods: privilegeForm.tags,
    privilegeValue: privilegeForm.value
  }
  privilegeLoading.value = true
  storyController.privilegeKeyWord(param).then(res => {
    if(res.code === 200){
      privilegeModal.value = false
      getStoryBoardByChapterId()
    }else {
      window.$message.error(res.msg)
    }
  }).finally(() => {
    privilegeLoading.value = false
  })
}



const batchInterrogate = () => {
  taskStatus.value = {
    successNum: 0,
    failNum: 0
  }
  batchInterrogateProgressModal.value = true
  const data = {
    storyId: props.story.id,
    skipFlag: 0
  }
  storyController.batchInterrogate(data,20 * 60 *1000,taskStatus).then(res => {
    if (res.code === 200) {
      getStoryBoardByChapterId()
    } else {
      window.$message.error(res.msg)
    }
  }).finally(() => {
    batchInterrogateProgressModal.value = false
  })

}


Bus.on('refreshStoryConfig', async () => {
    await getStoryPaintConfig()
})
</script>
